package com.wpre.booksystem.service;

import com.wpre.booksystem.mapper.UserMapper;
import com.wpre.booksystem.model.UserInfo;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-11-14
 * Time: 22:28
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    //检查密码是否正确
    public Boolean checkUserPassword(String username, String password, HttpSession session) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return false;
        }
        //2.从数据库中校验账号密码是否正确

        UserInfo userInfo = userMapper.selectUser(username);
        if (userInfo == null) {
            return false;
        }

        if (userInfo.getPassword().equals(password)) {
            //3.如果正确,存储session
            session.setAttribute("name", username);
            return true;
        }
        return false;
    }

    //注册功能
    public Boolean register(String username, String password, HttpSession session) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return false;
        }
        //在数据库中添加一条数据
        userMapper.insertUser(username, password);

        //设置session
        session.setAttribute("name", username);

        return true;
    }
}
